import React, { CSSProperties, ReactNode } from 'react';
import { Button, Text, ITouchEvent } from '@tarojs/components';
import { GStyleSheet, ThemeCompetent, DynamicColors } from '@/utils/DarkMode';

const dstyles = GStyleSheet.create({
  button: {
    backgroundColor: DynamicColors.tintColor,
    height: 44,
    borderRadius: 5,
    marginHorizontal: 40,
    justifyContent: 'center',
    alignItems: 'center',
    display: 'flex',
    width: '80%',
  },
  primary: {
    backgroundColor: 'rgba(0,0,0,0)',
    borderColor: DynamicColors.tintColor,
    borderWidth: 1,
    borderStyle: 'solid',
  },
  buttonText: {
    fontSize: 16,
    color: DynamicColors.normalBackgroundColor,
  },
  buttonTextPrimary: {
    color: DynamicColors.tintColor,
  },
});

interface IProps {
  disabled?: boolean;
  onPress?: (e: ITouchEvent) => void;
  text: string | ReactNode;
  style?: CSSProperties;
  fontSize?: number;
  primary?: boolean;
  textStyle?: CSSProperties;
}

@ThemeCompetent
class GButton extends React.Component<IProps, {}> {

  button: any;

  onPress = (e: ITouchEvent) => {
    const { onPress, disabled } = this.props;
    if (disabled === true) {
      return;
    }
    if (onPress) {
      onPress(e);
    }
  };

  render() {
    const styles = dstyles.style;
    const {
      text,
      style,
      fontSize,
      disabled,
      primary,
      textStyle,
      ...reset
    } = this.props;
    const buttonStyle = {
      ...styles.button,
      ...(primary ? styles.primary : {}),
      ...(disabled ? { opacity: 0.5 } : {}),
      ...style,
    };
    return (
      <Button
        {...reset}
        ref={c => (this.button = c)}
        disabled={disabled}
        onClick={this.onPress}
        style={buttonStyle}
      >
        {
          typeof text === 'string' ? (
            <Text style={{
              ...styles.buttonText,
              ...primary ? styles.buttonTextPrimary : {},
              ...fontSize ? { fontSize } : {},
              ...textStyle,
            }}
            >
              {text}
            </Text>
          ) : text
        }
      </Button>
    );
  }
}

const DeleteButton = (props: IProps) => {
  const { style: propsStyle } = props;
  const style = { ...propsStyle, backgroundColor: DynamicColors.deleteButton.value };
  // eslint-disable-next-line no-param-reassign
  props.style = style;
  return <GButton {...props} style={style} />;
};

export { GButton, DeleteButton };
